Page({
  data: {
    title: '', // 文章标题
    content: '', // 文章内容
    shareType: 'none', // 分享类型：word/sentence/none
    sharedWord: { // 分享的单词
      word: '',
      meaning: ''
    },
    sharedSentence: '', // 分享的句子
    selectedImages: [], // 选择的图片
    selectedTags: [], // 选择的标签
    customTag: '', // 自定义标签输入
    presetTags: ['学习心得', '单词分享', '语法讲解', '翻译练习', '口语练习', '听力技巧', '阅读理解', '写作技巧'], // 预设标签
    canPublish: false // 是否可以发布
  },

  onLoad: function(options) {
    this.updatePublishState();
  },

  onShow: function() {
    // 页面显示时重新检查发布状态
    this.updatePublishState();
    
    // 检查是否有分享数据
    this.handleShareData();
  },

  // 处理分享数据
  handleShareData: function() {
    const app = getApp();
    const shareData = app.globalData.shareData;
    
    if (shareData) {
      if (shareData.shareType === 'word' && shareData.word && shareData.meaning) {
        // 处理单词分享
        this.setData({
          shareType: 'word',
          sharedWord: {
            word: shareData.word,
            meaning: shareData.meaning
          }
        });
        
        wx.showToast({
          title: '单词已填入，可编辑或直接发布',
          icon: 'success',
          duration: 2000
        });
      } else if (shareData.shareType === 'sentence' && shareData.sentence) {
        // 处理句子分享
        this.setData({
          shareType: 'sentence',
          sharedSentence: shareData.sentence
        });
        
        wx.showToast({
          title: '翻译内容已填入，可编辑或直接发布',
          icon: 'success',
          duration: 2000
        });
      }
      
      // 清除分享数据，避免重复处理
      app.globalData.shareData = null;
      
      // 更新发布状态
      this.updatePublishState();
    }
  },

  // 标题输入
  onTitleInput: function(e) {
    this.setData({
      title: e.detail.value
    });
    this.updatePublishState();
  },

  // 内容输入
  onContentInput: function(e) {
    this.setData({
      content: e.detail.value
    });
    this.updatePublishState();
  },

  // 选择分享类型
  selectShareType: function(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      shareType: type
    });
    
    // 清空相关输入
    if (type !== 'word') {
      this.setData({
        sharedWord: { word: '', meaning: '' }
      });
    }
    if (type !== 'sentence') {
      this.setData({
        sharedSentence: ''
      });
    }
    
    this.updatePublishState();
  },

  // 单词输入
  onWordInput: function(e) {
    this.setData({
      'sharedWord.word': e.detail.value
    });
    this.updatePublishState();
  },

  // 释义输入
  onMeaningInput: function(e) {
    this.setData({
      'sharedWord.meaning': e.detail.value
    });
    this.updatePublishState();
  },

  // 句子输入
  onSentenceInput: function(e) {
    this.setData({
      sharedSentence: e.detail.value
    });
    this.updatePublishState();
  },

  // 选择图片
  chooseImages: function() {
    const that = this;
    wx.chooseMedia({
      count: 3 - this.data.selectedImages.length, // 最多选择3张
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        const newImages = res.tempFiles.map(file => file.tempFilePath);
        const updatedImages = [...that.data.selectedImages, ...newImages];
        that.setData({
          selectedImages: updatedImages.slice(0, 3) // 确保不超过3张
        });
      },
      fail: function(err) {
        console.error('选择图片失败:', err);
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    });
  },

  // 删除图片
  deleteImage: function(e) {
    const index = e.currentTarget.dataset.index;
    const images = [...this.data.selectedImages];
    images.splice(index, 1);
    this.setData({
      selectedImages: images
    });
  },

  // 切换标签选择
  toggleTag: function(e) {
    const tag = e.currentTarget.dataset.tag;
    let selectedTags = [...this.data.selectedTags];
    
    const index = selectedTags.indexOf(tag);
    if (index > -1) {
      selectedTags.splice(index, 1);
      wx.showToast({
        title: '标签已移除',
        icon: 'success',
        duration: 1000
      });
    } else {
      if (selectedTags.length < 5) { // 最多选择5个标签
        selectedTags.push(tag);
        wx.showToast({
          title: '标签已添加',
          icon: 'success',
          duration: 1000
        });
      } else {
        wx.showToast({
          title: '最多选择5个标签',
          icon: 'none'
        });
        return;
      }
    }
    
    this.setData({
      selectedTags: selectedTags
    });
    this.updatePublishState();
  },

  // 移除标签
  removeTag: function(e) {
    const tag = e.currentTarget.dataset.tag;
    const selectedTags = this.data.selectedTags.filter(t => t !== tag);
    
    this.setData({
      selectedTags: selectedTags
    });
    this.updatePublishState();
    
    wx.showToast({
      title: '标签已移除',
      icon: 'success',
      duration: 1000
    });
  },

  // 自定义标签输入
  onCustomTagInput: function(e) {
    this.setData({
      customTag: e.detail.value
    });
  },

  // 添加自定义标签
  addCustomTag: function() {
    const customTag = this.data.customTag.trim();
    if (!customTag) return;
    
    if (this.data.selectedTags.length >= 5) {
      wx.showToast({
        title: '最多选择5个标签',
        icon: 'none'
      });
      return;
    }
    
    if (this.data.selectedTags.includes(customTag)) {
      wx.showToast({
        title: '标签已存在',
        icon: 'none'
      });
      return;
    }
    
    const selectedTags = [...this.data.selectedTags, customTag];
    this.setData({
      selectedTags: selectedTags,
      customTag: ''
    });
    this.updatePublishState();
    
    wx.showToast({
      title: '自定义标签已添加',
      icon: 'success',
      duration: 1000
    });
  },

  // 更新发布状态
  updatePublishState: function() {
    const { title, content, shareType, sharedWord, sharedSentence } = this.data;
    let canPublish = title.trim().length > 0 && content.trim().length > 0;
    
    // 如果选择了特定分享类型，检查相应内容
    if (shareType === 'word') {
      canPublish = canPublish && sharedWord.word.trim().length > 0 && sharedWord.meaning.trim().length > 0;
    } else if (shareType === 'sentence') {
      canPublish = canPublish && sharedSentence.trim().length > 0;
    }
    
    this.setData({
      canPublish: canPublish
    });
  },

  // 发布内容
  publishContent: function() {
    if (!this.data.canPublish) {
      wx.showToast({
        title: '请完善内容',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({
      title: '发布中...'
    });
    
    // 模拟发布延时
    setTimeout(() => {
      // 生成新文章数据
      const newArticle = this.generateArticleData();
      
      // 保存到本地存储
      this.saveArticleToLocal(newArticle);
      
      wx.hideLoading();
      
      // 先清空表单
      this.resetForm();
      
      // 显示发布成功提示
      wx.showToast({
        title: '发布成功！',
        icon: 'success',
        duration: 2000,
        success: () => {
          // 1秒后询问是否跳转到社区
          setTimeout(() => {
            wx.showModal({
              title: '发布成功',
              content: '你的内容已发布，是否前往社区页面查看？',
              confirmText: '去看看',
              cancelText: '继续发布',
              success: (res) => {
                if (res.confirm) {
                  // 跳转到社区页面
                  wx.switchTab({
                    url: '/pages/community/community'
                  });
                }
                // 如果选择继续发布，则停留在当前页面（表单已清空）
              }
            });
          }, 1000);
        }
      });
    }, 500);
  },

  // 生成文章数据
  generateArticleData: function() {
    const userInfo = wx.getStorageSync('userInfo') || {
      nickname: '匿名用户',
      avatar: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
    };
    
    const now = new Date();
    const timeString = this.formatTime(now);
    
    // 生成唯一ID
    const articleId = 'user_' + now.getTime();
    
    const article = {
      id: articleId,
      title: this.data.title.trim(),
      content: this.data.content.trim(),
      fullContent: this.data.content.trim(), // 添加完整内容字段
      author: {
        id: 'current_user', // 当前用户ID
        name: userInfo.nickname,
        avatar: userInfo.avatar
      },
      publishTime: timeString,
      likeCount: 0,
      commentCount: 0,
      isLiked: false,
      isFollowed: false,
      tags: this.data.selectedTags,
      images: this.data.selectedImages.length > 0 ? this.data.selectedImages : null
    };
    
    // 添加分享内容
    if (this.data.shareType === 'word' && this.data.sharedWord.word && this.data.sharedWord.meaning) {
      article.sharedWord = {
        word: this.data.sharedWord.word.trim(),
        meaning: this.data.sharedWord.meaning.trim()
      };
    }
    
    if (this.data.shareType === 'sentence' && this.data.sharedSentence) {
      article.sharedSentence = this.data.sharedSentence.trim();
    }
    
    return article;
  },

  // 保存文章到本地存储
  saveArticleToLocal: function(article) {
    const userArticles = wx.getStorageSync('userPublishedArticles') || [];
    userArticles.unshift(article); // 添加到开头
    
    // 只保留最近50篇文章
    if (userArticles.length > 50) {
      userArticles.splice(50);
    }
    
    wx.setStorageSync('userPublishedArticles', userArticles);
  },

  // 重置表单
  resetForm: function() {
    this.setData({
      title: '',
      content: '',
      shareType: 'none',
      sharedWord: { word: '', meaning: '' },
      sharedSentence: '',
      selectedImages: [],
      selectedTags: [],
      customTag: '',
      canPublish: false
    });
    
    // 确保表单状态完全重置
    this.updatePublishState();
  },

  // 格式化时间
  formatTime: function(date) {
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / (1000 * 60));
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
    
    if (diffMins < 1) {
      return '刚刚';
    } else if (diffMins < 60) {
      return `${diffMins}分钟前`;
    } else if (diffHours < 24) {
      return `${diffHours}小时前`;
    } else if (diffDays < 30) {
      return `${diffDays}天前`;
    } else {
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${month}月${day}日`;
    }
  }
}) 